package com.ict.util;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;
import java.util.UUID;

/**
 * 服务通信的公钥私钥验签工具类
 */
public class RSAUtil {

    // 使用私钥生成签名
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    // 使用公钥验证签名
    public static boolean verify(String data, String signature, PublicKey publicKey) throws Exception {
        Signature sig = Signature.getInstance("SHA256withRSA");
        sig.initVerify(publicKey);
        sig.update(data.getBytes(StandardCharsets.UTF_8));
        return sig.verify(Base64.getDecoder().decode(signature));
    }

    // 生成随机的nonceId
    public static String generateNonceId() {
        return UUID.randomUUID().toString();
    }

    // 生成时间戳
    public static long generateTimestamp() {
        return System.currentTimeMillis();
    }
}
